package com.ibeeking.found.content.b.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.enums.PublishStatusEnum;

import com.ibeeking.found.common.enums.marketing.CouponTypeEnum;
import com.ibeeking.found.common.response.ResponseCodeEnum;
import com.ibeeking.found.common.utils.NumberUtils;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.content.api.common.dto.CouponInfoDTO;
import com.ibeeking.found.content.api.feign.ContentCouponBClient;
import com.ibeeking.found.content.b.rest.service.IBroadcastCouponService;
import com.ibeeking.found.content.service.common.dos.BroadcastCouponDO;
import com.ibeeking.found.content.service.common.param.BroadcastCouponParam;
import com.ibeeking.found.content.service.common.query.BroadcastCouponPageQuery;
import com.ibeeking.found.content.service.common.query.BroadcastCouponQuery;
import com.ibeeking.found.content.service.common.query.BroadcastGoodsQuery;
import com.ibeeking.found.content.service.common.vo.BroadcastCouponVO;
import com.ibeeking.found.content.service.mapper.BroadcastCouponMapper;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.log.utils.LogUtils;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.id.IdGenerator;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BroadcastCouponServiceImpl extends ServiceImpl<BroadcastCouponMapper, BroadcastCouponDO> implements IBroadcastCouponService {

    @Resource
    private BroadcastCouponMapper broadcastCouponMapper;

    @Resource
    private ContentCouponBClient contentCouponBClient;

    @Override
    public List<BroadcastCouponVO> list(BroadcastCouponQuery query) {
        LambdaQueryWrapper<BroadcastCouponDO> queryWrapper = new LambdaQueryWrapper<BroadcastCouponDO>()
                .eq(query.getId()!= null, BroadcastCouponDO::getId, query.getId())
                .eq(query.getCouponType()!= null, BroadcastCouponDO::getCouponType, query.getCouponType())
                .eq(query.getPublishStatus()!= null, BroadcastCouponDO::getPublishStatus, query.getPublishStatus())
                .like(StringUtils.isNotBlank(query.getCouponName()), BroadcastCouponDO::getCouponName, query.getCouponName())
                .orderByDesc(BroadcastCouponDO::getCreateTime);
        List<BroadcastCouponDO> broadcastCouponDOs = broadcastCouponMapper.selectList(queryWrapper);
        List<BroadcastCouponVO> broadcastCouponVOS = new ArrayList<>();
        if(Collections3.isNotEmpty(broadcastCouponDOs)){
            broadcastCouponVOS = broadcastCouponDOs.stream().map(d->{
                BroadcastCouponVO broadcastCouponVO = BeanUtil.convertBean(d, BroadcastCouponVO.class);
                broadcastCouponVO.setCouponTypeName(CouponTypeEnum.getEnum(d.getCouponType()).getLable());
                if(d.getCouponValue() != null) {
                    BigDecimal fCouponValue = NumberUtils.cent2Yuan(d.getCouponValue());
                    broadcastCouponVO.setCouponValueDesc(fCouponValue.toPlainString());
                }
                if(d.getCouponValue2() != null) {
                    BigDecimal fCouponValue = NumberUtils.cent2Yuan(d.getCouponValue2());
                    broadcastCouponVO.setCouponValueDesc(fCouponValue.toPlainString());
                }
                broadcastCouponVO.setPublishStatusDesc(PublishStatusEnum.getName(d.getPublishStatus()));
                return broadcastCouponVO;
            }).collect(Collectors.toList());
        }
        return broadcastCouponVOS;
    }

    @Override
    public Page<BroadcastCouponVO> pageList(BroadcastCouponPageQuery pageQuery) {
        LambdaQueryWrapper<BroadcastCouponDO> queryWrapper = new LambdaQueryWrapper<BroadcastCouponDO>()
                .eq(pageQuery.getId()!= null, BroadcastCouponDO::getId, pageQuery.getId())
                .eq(pageQuery.getCouponType()!= null, BroadcastCouponDO::getCouponType, pageQuery.getCouponType())
                .eq(pageQuery.getPublishStatus()!= null, BroadcastCouponDO::getPublishStatus, pageQuery.getPublishStatus())
                .like(StringUtils.isNotBlank(pageQuery.getCouponName()), BroadcastCouponDO::getCouponName, pageQuery.getCouponName())
                .orderByDesc(BroadcastCouponDO::getCreateTime);

        Page<BroadcastCouponDO> pages = broadcastCouponMapper.selectPage(new Page<BroadcastCouponDO>(pageQuery.getPageNum(), pageQuery.getPageSize()), queryWrapper);
        Page<BroadcastCouponVO> broadcastCouponVOPage = BeanUtil.convertPage(pages, BroadcastCouponVO.class);
        List<BroadcastCouponVO> records = broadcastCouponVOPage.getRecords();
        if (Collections3.isNotEmpty(records)) {
            records.stream().forEach(d->{
                d.setCouponTypeName(CouponTypeEnum.getEnum(d.getCouponType()).getLable());
                if(d.getCouponValue() != null) {
                    BigDecimal fCouponValue = NumberUtils.cent2Yuan(d.getCouponValue());
                    d.setCouponValueDesc(fCouponValue.toPlainString());
                }
                if(d.getCouponValue2() != null) {
                    BigDecimal fCouponValue = NumberUtils.cent2Yuan(d.getCouponValue2());
                    d.setCouponValueDesc(fCouponValue.toPlainString());
                }
                d.setPublishStatusDesc(PublishStatusEnum.getName(d.getPublishStatus()));
            });
            broadcastCouponVOPage.setRecords(records);
        }
        return broadcastCouponVOPage;
    }

    @Override
    public Boolean add(BroadcastCouponParam broadcastCouponParam) {
        checkUnique(broadcastCouponParam);
        BroadcastCouponDO broadcastCouponDO = BeanUtil.convertBean(broadcastCouponParam, BroadcastCouponDO.class);
        broadcastCouponDO.setCreateBy(UserUtils.getUserId());
        broadcastCouponDO.setCreateTime(LocalDateTime.now());
        broadcastCouponDO.setModifyTime(LocalDateTime.now());
        return broadcastCouponMapper.insert(broadcastCouponDO) > 0;
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Boolean batchAdd(List<String> couponIdList) {
        List<Long> couponsIds = couponIdList.stream().map(Long::valueOf).collect(Collectors.toList());

        if(Collections3.isEmpty(couponsIds)) return false;
        ResponseResult<List<CouponInfoDTO>> couponInfoDTOSResult = contentCouponBClient.queryInfoByIds(couponsIds);
        if(couponInfoDTOSResult == null || !ResponseCodeEnum.SUCCESS.getCode().equals(couponInfoDTOSResult.getCode()))  return false;
        List<CouponInfoDTO> couponInfoDTOList = couponInfoDTOSResult.getData();
        if(Collections3.isEmpty(couponInfoDTOList)) return false;
        BroadcastGoodsQuery query = new BroadcastGoodsQuery();
        query.setPublishStatus(PublishStatusEnum.ENABLE.getValue());
        //List<BroadcastGoodsVO> savedBroadcastGoodsVOS = this.getBean().list(query);
        //Map<Long, String> articleCountMap = savedBroadcastGoodsVOS.stream().collect(Collectors.toMap(BroadcastGoodsVO::getId,BroadcastGoodsVO::getGoodsName));
        List<BroadcastCouponDO> broadcastCouponDOS = new ArrayList<BroadcastCouponDO>();
        broadcastCouponDOS = couponInfoDTOList.stream().map(d->{
            // if(articleCountMap.containsKey(d.getId())) {
            BroadcastCouponDO broadcastCouponDO = new BroadcastCouponDO();
            broadcastCouponDO.setId(IdGenerator.getId());
            broadcastCouponDO.setCouponId(d.getId());
            broadcastCouponDO.setCouponName(d.getName());
            broadcastCouponDO.setCouponType(CouponTypeEnum.getEnum(d.getCouponTypeCode()).getCode());
            broadcastCouponDO.setCouponValue(d.getWorth());
            broadcastCouponDO.setCouponThumb(d.getPic());
            broadcastCouponDO.setCouponPagePath(d.getPagePath());
            broadcastCouponDO.setPublishStatus(PublishStatusEnum.DISABLE.getValue());
            broadcastCouponDO.setCreateBy(UserUtils.getUserId());
            broadcastCouponDO.setCreateTime(LocalDateTime.now());
            broadcastCouponDO.setModifyTime(LocalDateTime.now());
            return broadcastCouponDO;

        }).collect(Collectors.toList());
        LogUtils.info("==========broadcastGoodsDOS:{}===========",JsonUtils.toJsonStr(broadcastCouponDOS));
        return broadcastCouponMapper.insertBatchSomeColumn(broadcastCouponDOS) > 0;
    }

    @Override
    public Boolean modify(BroadcastCouponParam broadcastCouponParam) {
        checkUnique(broadcastCouponParam);
        BroadcastCouponDO broadcastCouponDO = BeanUtil.convertBean(broadcastCouponParam, BroadcastCouponDO.class);
        broadcastCouponDO.setModifyBy(UserUtils.getUserId());
        broadcastCouponDO.setModifyTime(LocalDateTime.now());
        return broadcastCouponMapper.updateById(broadcastCouponDO) > 0;
    }

    @Override
    public BroadcastCouponVO view(Long id) {
        BroadcastCouponDO broadcastCouponDO = broadcastCouponMapper.selectById(id);
        BroadcastCouponVO broadcastCouponVO = JsonUtils.fromJson(broadcastCouponDO, BroadcastCouponVO.class);
        return broadcastCouponVO;
    }

    @Override
    public Boolean del(Long id) {
        return broadcastCouponMapper.deleteById(id) > 0;
    }
    /***
     * 发布状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean changePublishStatus(Long id, Integer status) {
        BroadcastCouponDO broadcastCouponDO = broadcastCouponMapper.selectById(id);
        broadcastCouponDO.setId(id);
        broadcastCouponDO.setPublishStatus(status);
        broadcastCouponDO.setModifyTime(LocalDateTime.now());
//        if (PublishStatusEnum.ENABLE.getValue().equals(status)) {
//            broadcastGoodsDO.setPublishTime(LocalDateTime.now());
//        }
        /**
         * 只有点发布时候，才能把商品信息推送到微信直播平台
         */
        return broadcastCouponMapper.updateById(broadcastCouponDO) > 0;
    }
    /**
     * 校验唯一性
     *
     * @param param
     */
    public void checkUnique(BroadcastCouponParam param) {
        LambdaQueryWrapper<BroadcastCouponDO> queryWrapper = new LambdaQueryWrapper<BroadcastCouponDO>()
                .ne(param.getId() != null, BroadcastCouponDO::getId, param.getId())
                .eq(StringUtils.isNotBlank(param.getCouponName()), BroadcastCouponDO::getCouponName, param.getCouponName());
        List<BroadcastCouponDO> dos = broadcastCouponMapper.selectList(queryWrapper);
        if (Collections3.isNotEmpty(dos)) {
            throw new BusinessException("已经存在相同名字的商品!");
        }
    }
}

